<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { Lunar } from 'lunar-javascript'

const now = ref({
  date: '',
  time: '',
  lunar: '',
  festival: '',
})

let timer: number | undefined

function ensureMonthHasYue(monthStr: string) {
  if (!monthStr) return ''
  return monthStr.includes('月') ? monthStr : `${monthStr}月`
}

function updateNow() {
  const date = new Date()
  const y = date.getFullYear()
  const m = (date.getMonth() + 1).toString().padStart(2, '0')
  const d = date.getDate().toString().padStart(2, '0')
  const h = date.getHours().toString().padStart(2, '0')
  const min = date.getMinutes().toString().padStart(2, '0')
  const s = date.getSeconds().toString().padStart(2, '0')

  // 公历
  const dateStr = `${y}-${m}-${d}`
  const timeStr = `${h}:${min}:${s}`

  // 农历（确保月份带“月”）
  const lunar = Lunar.fromDate(date)
  const rawMonth = lunar.getMonthInChinese()
  const monthWithYue = ensureMonthHasYue(rawMonth)
  const day = lunar.getDayInChinese()
  const lunarStr = `${monthWithYue}${day}`

  // 节日（优先农历，其次公历）
  const fest = lunar.getFestivals()[0] || lunar.getSolar().getFestivals()[0] || ''

  now.value = {
    date: dateStr,
    time: timeStr,
    lunar: lunarStr,
    festival: fest,
  }
}

onMounted(() => {
  updateNow()
  timer = window.setInterval(updateNow, 16) // 每秒更新
})

onUnmounted(() => {
  if (timer) clearInterval(timer)
})
</script>

<template>
  <div class="calendar-bar">
    <span class="date">{{ now.date }}</span>
    <span class="time">{{ now.time }}</span>
    <span class="lunar">农历 {{ now.lunar }}</span>
    <span v-if="now.festival" class="festival">🎉 {{ now.festival }}</span>
  </div>
</template>

<style scoped>
.calendar-bar {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 14px;
  background: #f5f5f5;
  padding: 6px 12px;
  border-radius: 6px;
  color: #333;
  cursor: default;
}
.festival {
  color: #d9534f;
  font-weight: bold;
}
</style>
